package handler

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"zk12.27/api/request"
	"zk12.27/glodal"
	"zk12.27/internal/model"
)

func GiftAdd(c *gin.Context) {
	var req request.GiftAdd
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	gift := model.Gift{
		GiftName:      req.GiftName,
		GiftNotes:     req.GiftNotes,
		GiftUserId:    req.GiftUserId,
		ReceiveGiftId: req.ReceiveGiftId,
	}
	err = glodal.DB.Create(&gift).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "直播间创建失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": gift.ID,
	})
}

func GiftList(c *gin.Context) {
	var req request.GiftList
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var gift []model.Gift
	err = glodal.DB.Where("receive_gift_id = ?", req.ReceiveGiftId).Find(&gift).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "该直播间不存在",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": gift,
	})
}

func GiftUpdate(c *gin.Context) {
	var req request.GiftUpdate
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	gift := model.Gift{
		Model:     gorm.Model{ID: req.GiftId},
		GiftNotes: req.GiftNotes,
	}
	err = glodal.DB.Updates(&gift).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "礼物备注修改失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "礼物修改成功",
		"data": gift,
	})
}

func GiftDelete(c *gin.Context) {
	var req request.GiftDelete
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var gift model.Gift
	err = glodal.DB.Where("id = ?", req.GiftId).First(&gift).Error
	if gift.ID == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "该礼物不存在",
			"data": nil,
		})
		return
	}
	err = glodal.DB.Delete(&gift).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "礼物删除失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": gift.ID,
	})
}
